package com.atguigu.day04;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;

public class Example10 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<String> streamSource = env.readTextFile("D:\\WebSite\\flink\\flink\\java_flink\\src\\main\\resources\\UserBehavior.csv");
        streamSource
                .map(x -> {
                    String[] arr = x.split(",");
                    return new UserBehavior(
                            arr[0],
                            arr[1],
                            arr[2],
                            arr[3],
                            Long.parseLong(arr[4]));
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<UserBehavior>forMonotonousTimestamps()
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                                    @Override
                                    public long extractTimestamp(UserBehavior element, long recordTimestamp) {
                                        return element.timestamp;
                                    }
                                }))
                .filter(x -> x.behavior.equals("pv"))
                .keyBy(x -> x.itemId)
                .window(SlidingEventTimeWindows.of(Time.hours(1), Time.minutes(5)))
                .aggregate(new AggregateFunction<UserBehavior, Long, Long>() {
                    @Override
                    public Long createAccumulator() {
                        return 0L;
                    }

                    @Override
                    public Long add(UserBehavior value, Long accumulator) {
                        return accumulator + 1L;
                    }

                    @Override
                    public Long getResult(Long accumulator) {
                        return accumulator;
                    }

                    @Override
                    public Long merge(Long a, Long b) {
                        return null;
                    }
                }, new ProcessWindowFunction<Long, ItemViewCount, String, TimeWindow>() {
                    @Override
                    public void process(String key, Context context, Iterable<Long> elements, Collector<ItemViewCount> out) throws Exception {
                        out.collect(
                                new ItemViewCount(
                                        key,
                                        context.window().getStart(),
                                        context.window().getEnd(),
                                        elements.iterator().next()
                                )
                        );
                    }
                })
                .keyBy(x -> x.endTime)
                .process(new KeyedProcessFunction<Long, ItemViewCount, String>() {
                    private ListState<Tuple2<String, Long>> listState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        listState = getRuntimeContext().getListState(new ListStateDescriptor<Tuple2<String, Long>>(
                                "list_Stage", Types.TUPLE(Types.STRING, Types.LONG)
                        ));
                    }

                    @Override
                    public void processElement(ItemViewCount value, Context ctx, Collector<String> out) throws Exception {
                        ctx.timerService().registerEventTimeTimer(value.endTime + 1L);
                        listState.add(Tuple2.of(value.itemId, value.count));
                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        Iterator<Tuple2<String, Long>> iterator = listState.get().iterator();
                        ArrayList<Tuple2<String, Long>> list = new ArrayList<>();
                        while (iterator.hasNext()) {
                            list.add(iterator.next());
                        }
                        listState.clear();
                        list.sort((o1, o2) -> -(int) (o1.f1 - o2.f1));
                        StringBuilder sb = new StringBuilder();
                        sb
                                .append("****************************************\n");
                        for (int i = 0; i < 3; i++) {
                            sb.append("窗口结束时间：").append(new Timestamp(timestamp - 1)).append("第").append(i + 1).append("名   商品ID：").append(list.get(i).f0).append("  浏览总量： ").append(list.get(i).f1).append("\n");
                        }
                        sb
                                .append("****************************************\n");
                        out.collect(sb.toString());
                    }
                })
                .print();
        env.execute();


    }

    public static class ItemViewCount {
        public String itemId;
        public Long startTime;
        public Long endTime;
        public Long count;

        public ItemViewCount() {
        }

        @Override
        public String toString() {
            return "ItemViewCount{" +
                    "itemId='" + itemId + '\'' +
                    ", startTime=" + new Timestamp(startTime) +
                    ", endTime=" + new Timestamp(endTime) +
                    ", count=" + count +
                    '}';
        }

        public ItemViewCount(String itemId, Long startTime, Long endTime, Long count) {
            this.itemId = itemId;
            this.startTime = startTime;
            this.endTime = endTime;
            this.count = count;
        }
    }


    public static class UserBehavior {
        public String userId;
        public String itemId;
        public String categoryId;
        public String behavior;
        public Long timestamp;

        @Override
        public String toString() {
            return "UserBehavior{" +
                    "userId='" + userId + '\'' +
                    ", itemId='" + itemId + '\'' +
                    ", categoryId='" + categoryId + '\'' +
                    ", behavior='" + behavior + '\'' +
                    ", timestamp=" + new Timestamp(timestamp) +
                    '}';
        }

        public UserBehavior() {
        }

        public UserBehavior(String userId, String itemId, String categoryId, String behavior, Long timestamp) {
            this.userId = userId;
            this.itemId = itemId;
            this.categoryId = categoryId;
            this.behavior = behavior;
            this.timestamp = timestamp * 1000L;
        }
    }
}
